package com.yy.service;

import com.yy.mapper.RoleMapper;
import com.yy.pojo.Role;
import com.yy.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: yy
 * @Date 2021/11/14 12:50
 */
@Component
@Service
public class RoleService {
    @Resource
    @Autowired
    private RoleMapper roleMapper;

//    public List<Role> getRoleList() {
//        return roleMapper.getRoleList();
//    }
//
//
    public Role roleGetByUid(String uid) {
        Role result = roleMapper.ridFindByUid(uid);
        if (result == null){
            throw new RoleNotFoundException("角色数据不存在");
        }

        Role role = new Role();
        role.setRoleName(result.getRoleName());
        role.setRoleId(result.getRoleId());

        return role;
    }



    public Role roleGetByUname(String uname) {
        Role result = roleMapper.ridFindByUname(uname);
        if (result == null){
            throw new UserRoleNotFoundException("该用户尚未分配角色");
        }
        Role role = new Role();
        role.setRoleName(result.getRoleName());
        role.setRoleId(result.getRoleId());
        return role;
    }



    public List<Role> getRoleList() {
        List<Role> list = roleMapper.findRoleList();
        for (Role role : list){

        }
        return list;
    }



    public void deleteRole(String rname) {
        Role result = roleMapper.findByRname(rname);
        if (result == null){
            throw new RoleNotFoundException("角色数据不存在");
        }
        Integer rows = roleMapper.deleteByRname(rname);
        if (rows != 1){
            throw new DeleteException("删除数据时产生未知异常");
        }
    }


    public Role getByRid(String rname) {
        Role result = roleMapper.findByRname(rname);
        if (result == null){
            throw new RoleNotFoundException("角色数据不存在");
        }
        Role role = new Role();
        role.setRoleId(result.getRoleId());
        role.setRoleName(result.getRoleName());
        return role;
    }


    public void addRole(Role role) {
        String roleid = role.getRoleId();
        String rolename = role.getRoleName();
        String roledescribe = role.getRoleDescribe();
        Role result = roleMapper.findByRname(rolename);
        if (result != null){
            throw new RoleNameDoplicatedException("尝试添加的角色名"+ rolename + "已经被占用");
        }
        Integer rows = roleMapper.addRole(role);
        if (rows != 1){
            throw new InsertException("添加角色时产生未知异常");
        }
    }


    public List<Role> roleFoundByUname(String username) {
        List<Role> list = roleMapper.roleFindByUname(username);
        for (Role role : list){

        }
        return list;
    }

    public List<Role> getPower(){
        List<Role> list = roleMapper.findPower();
        return list;
    }
}
